<?php
/**
 * Author: ChenGuangHui
 * Email：13035809409@163.com
 * Date Time: 2021/4/30 18:03
 */


namespace App\Logic\Common;

use App\Enums\HttpCode;
use App\Events\LoginEvent;
use App\Logic\CommLogic;
use App\Models\Staffer\Staffer;
use App\Models\Tenant;
use App\Services\VerifyService;
use Illuminate\Database\Eloquent\Builder;

class RegisterLogic extends CommLogic
{
    /**
     * @param $params
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function login($params)
    {
        $account = $params['account'];
        (new VerifyService())->checkImgVerify($params['guidCode'], $params['verifyGuid']);

        $userInfo = Staffer::query()->where(function (Builder $query) use ($account) {
            $query->where('email', $account);
        })->orWhere(function (Builder $query) use ($account) {
            $query->where('mobile', $account);
        })->first();
        
        abort_unless($userInfo, HttpCode::SERVER_ERROR, '账号不存在！');
        abort_unless($userInfo->status !== 1, HttpCode::SERVER_ERROR, '账号状态异常，请联系管理员！');

        $tenant = Tenant::query()->where('id', $userInfo->tenant_id)->first();
        abort_unless($tenant, HttpCode::SERVER_ERROR, '账号所属异常！');
        abort_unless($tenant->status !== 1, HttpCode::SERVER_ERROR, '平台状态异常，请联系管理员！');

        $jwt_token = null;
        filter_var($account, FILTER_VALIDATE_EMAIL) ?
            $credentials['email'] = $account :
            $credentials['mobile'] = $account;

        //接收传来的值
        $credentials['password'] = $params['password'];
        abort_if(!$jwt_token = auth()->attempt($credentials), HttpCode::SERVER_ERROR, '密码不正确！');

        // 触发登录事件广播
        // broadcast(new LoginEvent());

        $user = auth('api')->user();
        $user->avatar_url = json_decode($user->avatar_url, true);
        return array(
            'token' => $jwt_token,
            'userInfo' => auth('api')->user(),
            'auths' => ['register.verifyGuid','register.verifyGuid']
        );
    }

    /**
     * 修改密码
     * 
     * @author ChenGuangHui
     * @dateTime 2023-03-06
     * @param [type] $params
     */
    public function fixPassW($params)
    {
        $userInfo = Staffer::query()->where('id', auth('api')->id())->first();
        abort_unless($userInfo, HttpCode::SERVER_ERROR, '账号不存在！');
        abort_unless($userInfo->status !== 1, HttpCode::SERVER_ERROR, '账号状态异常，请联系管理员！');

        //接收传来的值
        $credentials['password'] = $params['password'];
        abort_if(!$jwt_token = auth()->attempt(['password' => $params['password'], 'account' => $userInfo->account]), HttpCode::SERVER_ERROR, '密码不正确！');
        # code...
        abort_if($params['new_password'] <> $params['pre_password'], HttpCode::SERVER_ERROR, '两次输入的密码不一致');
        
        $result = Staffer::query()->where('id', auth('api')->id())->update([
            'password' => bcrypt($params['new_password'])
        ]);
        
        return $result;
    }
}
